﻿#include "AsioIOServicePool.h"
#include <memory>

AsioIOServicePool::AsioIOServicePool(std::size_t size)
    : _ioServices(size), _works(size), _nextIOService(0) {
  for (std::size_t i = 0; i < size; ++i) {
    _works[i] = std::make_unique<Work>(boost::asio::make_work_guard(_ioServices[i]));
  }

  for (std::size_t i = 0; i < size; ++i) {
    _threads.emplace_back([this, i]() { _ioServices[i].run(); });
  }
}

AsioIOServicePool::~AsioIOServicePool() {
  Stop();
  std::cout << "---------------- AsioIOServicePool destruct ----------------"
            << std::endl;
}

boost::asio::io_context &AsioIOServicePool::GetIOService() {
  auto &service = _ioServices[_nextIOService++];
  if (_nextIOService >= _ioServices.size()) {
    _nextIOService = 0;
  }
  return service;
}

void AsioIOServicePool::Stop() {
     // 1. 先停止所有 io_context
    for (auto &io_service : _ioServices) {
        io_service.stop();
    }

    // 2. 释放 work 对象（不再需要）
    for (auto &work : _works) {
        work.reset();
    }

  for (auto &t : _threads) {
    t.join();
  }
}
